package com.yuneec.fly.presenters;

import android.app.Activity;
import android.text.TextUtils;

import com.yuneec.droneservice.command.CommandListener;
import com.yuneec.droneservice.command.GetCameraInfo;
import com.yuneec.droneservice.model.CameraInfo;
import com.yuneec.droneservice.model.CameraScanResult;
import com.yuneec.droneservice.request.IResponse;
import com.yuneec.fly.GlobalParams;
import com.yuneec.fly.events.EventBusFactory;
import com.yuneec.fly.events.commandEvent.SendCommandEvent;
import com.yuneec.fly.events.uiEvent.BindEvent;
import com.yuneec.fly.events.uiEvent.CameraConnectChangedEvent;
import com.yuneec.fly.events.uiEvent.OnResetEvent;
import com.yuneec.fly.events.uiEvent.ProgressEvent;
import com.yuneec.fly.events.uiEvent.ReflushEvent;
import com.yuneec.fly.events.uiEvent.ResetEvent;
import com.yuneec.fly.events.uiEvent.ScanEvent;
import com.yuneec.fly.events.uiEvent.SetWifiConfigurationEvent;
import com.yuneec.fly.events.uiEvent.ShowToastEvent;
import com.yuneec.fly.utils.CameraHelper;
import com.yuneec.fly.utils.inject.WifiPasswordsSaver;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import static com.yuneec.fly.GlobalParams.connectedCamera;

/**
 * Created by zd.zhang on 2016/7/15.
 */
public class BindCameraPresenter extends AbstractBindPresenter {
    private Activity activity;

    public BindCameraPresenter(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void start(String bind) {
        super.start(bind);
        EventBusFactory.getUiBus().register(this);
        CameraHelper.getInstance().start();
        CameraHelper.getInstance().setCameraListener(new CameraHelper.CameraListener() {
            @Override
            public void onFinishScan(ArrayList<CameraScanResult> wifis) {
                EventBusFactory.getUiBus().post(new ReflushEvent());
                resetState();
            }

            @Override
            public void onReset() {
                EventBusFactory.getUiBus().post(new OnResetEvent(true));
                resetState();
//                EventBusFactory.getUiBus().post(new ScanEvent());
            }

            @Override
            public void onConnectWifiSuccess(String wifi) {
                BindEvent e = new BindEvent();
                e.state = BindEvent.STATE_BINDED;
                e.tag = getCurrentBind();
                EventBusFactory.getUiBus().post(e);
                toast("连接成功");
            }

            @Override
            public void onConnectWifiFail(int errorCode) {
                resetState();
                EventBusFactory.getUiBus().post(new ProgressEvent());
//                CameraHelper.getInstance().scan();
                toast("连接失败:"+errorCode);
            }

            @Override
            public void onConnectWifiTime() {
                resetState();
                EventBusFactory.getUiBus().post(new ProgressEvent());
//                CameraHelper.getInstance().scan();
                toast("连接超时");
            }
        });
    }

    @Override
    public void stop() {
        super.stop();
        EventBusFactory.getUiBus().unregister(this);
        CameraHelper.getInstance().stop();
        CameraHelper.getInstance().setCameraListener(null);
    }

    @Override
    public List getDatas() {
        return CameraHelper.getInstance().getCameras();
    }

    @Override
    public boolean removeIndex(int index) {
        if (index >= 0 && CameraHelper.getInstance().getCameras() != null && CameraHelper.getInstance().getCameras().size() > index) {
            CameraHelper.getInstance().getCameras().remove(index);
            return true;
        }
        return false;
    }

    @Override
    public String getCurrentBind() {
        connectedCamera = CameraHelper.getInstance().getCurrentBind();
        if (!TextUtils.isEmpty(connectedCamera)) {
            EventBusFactory.getUiBus().post(new CameraConnectChangedEvent());
            return connectedCamera;
        }
        return null;
    }

    @Override
    public String getName(int position) {
        if (CameraHelper.getInstance().getCameras().size() > 0 && CameraHelper.getInstance().getCameras().get(position) != null) {
            return CameraHelper.getInstance().getCameras().get(position).getSsid();
        } else {
            return "";
        }
    }

    @Override
    public int getSize() {
        return CameraHelper.getInstance().getCameras().size();
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void scan(ScanEvent event) {
        if (!checkState(STATE_SCAN)) {
            return;
        }
        EventBusFactory.getCommandBus().post(new SendCommandEvent(new GetCameraInfo(), new CommandListener<CameraInfo>() {
            @Override
            public void onSuccess(IResponse<CameraInfo> response) {
                CameraInfo cameraInfo = response.getParam();
                if (!TextUtils.isEmpty(cameraInfo.getSsid())) {

                    GlobalParams.connectedCamera = cameraInfo.getSsid();
                    EventBusFactory.getUiBus().post(new CameraConnectChangedEvent());
                }
                CameraHelper.getInstance().scan();
            }

            @Override
            public void onError(int errorCode) {
                CameraHelper.getInstance().scan();
            }

            @Override
            public void onTimeout() {
                CameraHelper.getInstance().scan();
            }
        }));
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onReset(ResetEvent event) {
        if (!checkState(STATE_RESET)) {
            return;
        }
        CameraHelper.getInstance().reset();
    }


    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onBind(BindEvent event) {
        if (!checkState(STATE_BIND)) {
            return;
        }
        if (event.state == BindEvent.STATE_BIND && mChecked >= 0 && CameraHelper.getInstance().getCameras().size() > mChecked) {
            String res = CameraHelper.getInstance().getCameras().get(mChecked).getSsid();
            WifiPasswordsSaver.WifiPassword pas = CameraHelper.getInstance().getPassword(res);
            if (pas != null) {
                CameraHelper.getInstance().connectCamera(pas.ssid, pas.password);
                return;
            }
            SetWifiConfigurationEvent setWifiConfigurationEvent = new SetWifiConfigurationEvent();
            setWifiConfigurationEvent.tag = SetWifiConfigurationEvent.SET_PASSWORD;
            setWifiConfigurationEvent.obj = res;
            EventBusFactory.getUiBus().post(setWifiConfigurationEvent);
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void wifiSet(SetWifiConfigurationEvent event) {
        if (event.tag == SetWifiConfigurationEvent.ADD_CONFIGURATION && event.obj != null) {
            String res = CameraHelper.getInstance().getCameras().get(mChecked).getSsid();
            String password = event.obj.toString();
            WifiPasswordsSaver.WifiPassword pas = new WifiPasswordsSaver.WifiPassword(res, password);
            CameraHelper.getInstance().saveWifiPassword(pas);
            CameraHelper.getInstance().connectCamera(res, password);
        }
    }

    private void toast(final String msg) {
        EventBusFactory.getUiBus().post(new ShowToastEvent(msg));
    }
}
